<!--
 * @Description: 用户机构授权
 * @Author: DHL
 * @Date: 2022-04-06 15:14:56
 * @LastEditors: DHL
 * @LastEditTime: 2022-08-10 13:29:10
-->

<template>
  <tw-dialog
    v-model="visible"
    :title="title"
    :loading="loading"
    width="500px"
    height="650px"
    customClass="user-org-grant-wrapper"
    @close="handleClose"
  >
    <el-alert title="授权机构将同步调整已授权角色" type="error" :closable="false"> </el-alert>

    <organizationTree
      ref="orgTreeRef"
      :draggable="false"
      @nodeClick="handleNodeClick"
    ></organizationTree>

    <template #footer>
      <el-button @click="handleClose()">取 消</el-button>
      <el-button type="primary" @click="handleSubmit()"> 提 交 </el-button>
    </template>
  </tw-dialog>
</template>

<script setup lang="ts">
  import { computed, reactive, ref } from 'vue'
  import organizationTree from '../../components/organizationTree.vue'
  import type Node from 'element-plus/es/components/tree/src/model/node'
  import { UserModel } from '/@/api/system/model/userModel'
  import { apiUserUpdateUserOrgs } from '/@/api/system/user'
  import { ElMessage } from 'element-plus'
  import { assign } from 'lodash-es'
  import { apiOrganizationSearchUserOrgs } from '/@/api/system/organization'
  import { arraySerialize } from '/@/utils/twUtils'

  const loading = ref(true)

  /**
   * 显示弹框
   */
  const visible = ref(false)

  const orgTreeRef = ref()

  /**
   * 用户
   */
  const user = reactive({ id: '', name: '', orgId: '' })

  /**
   * 标题
   */
  const title = computed(() => {
    return `用户：${user.name} 授权机构`
  })

  /**
   * 选中的组织机构
   */
  let selectOrg: any = {}

  /**
   * 显示弹框
   */
  function handleOpen(userParams: UserModel) {
    assign(user, userParams)

    visible.value = true

    apiOrganizationSearchUserOrgs(user.id)
      .then((result) => {
        if (result?.success) {
          orgTreeRef.value.setChecked(arraySerialize(result.data, 'id'))
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  /**
   * 关闭弹框
   */
  function handleClose() {
    visible.value = false
  }

  /**
   * 节点点击事件
   */
  function handleNodeClick(treeNode?: Node) {
    selectOrg = treeNode ? treeNode : {}
  }

  /**
   * 提交
   */
  function handleSubmit() {
    loading.value = true
    apiUserUpdateUserOrgs(user.id, selectOrg.id)
      .then((result) => {
        if (result?.success) {
          ElMessage.success(result.message)
        } else {
          ElMessage.error(result?.message)
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  defineExpose({ handleOpen })
</script>

<style lang="scss">
  .user-org-grant-wrapper {
    .el-alert {
      margin-bottom: 8px;
    }
  }
</style>
